package com.example.litehdfs.service.impl;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.example.litehdfs.config.B2BServiceException;
import com.example.litehdfs.config.CodeConstant;
import com.example.litehdfs.mapper.UsersMapper;
import com.example.litehdfs.model.dto.UserInfo;
import com.example.litehdfs.model.dto.UserLoginInfo;
import com.example.litehdfs.model.req.UserLoginReq;
import com.example.litehdfs.service.UserService;
import com.example.litehdfs.util.PwdUtil;
import com.example.litehdfs.util.UserCacheUtil;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserCacheUtil userCacheUtil;
	@Autowired
	private UsersMapper userMapper;
	@Value("${server-root}")
	private String serverRoot;
	
	@Override
	public UserLoginInfo login(UserLoginReq req) {
		
		UserInfo user = userMapper.getUserByPhone(req.getPhoneNumber());
		if(user == null) {
			throw new B2BServiceException("账户不存在");
		}
		if(!PwdUtil.validateHash(req.getPassword(), user.getPassword())) {
			throw new B2BServiceException("密码错误");
		}
		
		if(!user.getStatus().equals(1)) {
			throw new B2BServiceException("账户被冻结，请联系管理员");
		}
		
		//登录成功
		String token = UUID.randomUUID().toString().replace("-","");
		
		UserLoginInfo info = new UserLoginInfo();
		BeanUtil.copyProperties(user, info, true);
		info.setAvatar(serverRoot+user.getAvatar());
		info.setToken(token);
		long tokenExpireTime = 7*24*3600;//7天
		info.setTokenExpireTime(tokenExpireTime);
		userCacheUtil.putUserInfo(CodeConstant.USER_LOGIN_TOKEN+token, info,tokenExpireTime);
		
		return info;
	}


	@Override
	public UserLoginInfo getUserInfo() {
		UserLoginInfo userInfo = userCacheUtil.getUserInfo();
		return userInfo;
	}

	
	
}
